package com.atguigu.orderservice.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.atguigu.commonutils.JwtUtil;
import com.atguigu.commonutils.Result;
import com.atguigu.orderservice.entity.Order;
import com.atguigu.orderservice.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author haoyue1573
 * @since 2023-03-24
 */
@RestController
@RequestMapping("/orderservice/order")
ResultssOrigin
public class OrderController {

	@Resource
	private OrderService orderService;

	//根据课程id和用户id创建订单，返回订单id
	@PostMapping("createOrder/{courseId}")
	public Result save(@PathVariable("courseId") String courseId,HttpServletRequest request) {
		 //获取请求头的用户信息
		String token = request.getHeader("token");
		if (token==null){
			return Result.error().message("用户未登录");
		}
		Claims claims = null;
		try {
			claims = JwtUtil.parseJWT(token);
			String userId = claims.getSubject();
			String orderId = orderService.saveOrder(courseId,userId);
			return Result.ok().data("orderId", orderId);

		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return Result.error().message("支付失败");
	}

	@GetMapping("getOrder/{orderNo}")
	public Result get(@PathVariable("orderNo") String orderNo) {
		QueryWrapper<Order> wrapper = new QueryWrapper<>();
		wrapper.eq("order_no",orderNo);
		Order order = orderService.getOne(wrapper);
		return Result.ok().data("item", order);
	}


	@GetMapping("isBuyCourse/{courseId}/{memberId}")
	public boolean isBuyCourse(@PathVariable String courseId,@PathVariable String memberId){
		//订单状态是1表示支付成功
		int count = orderService.count(new QueryWrapper<Order>().eq("member_id", memberId).eq("course_id", courseId).eq("status", 1));
		if(count>0) {
			return true;
		} else {
			return false;
		}

	}
}

